using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb;
using Nsb.Classes;
using ThemeChain;
using WhirliGig.Classes;
using Yoshi.Classes;
using jQueryApi;

namespace PlayNexus.Clusters
{
    [IgnoreNamespace]
    public class Links : Cluster
    {
        private readonly Dictionary _options;

        public Links(Dictionary options)
        {
            Element = jQuery.FromHtml("<div id='TopBar' style='position: relative; width: 100%; height: 100%; display: block;'/>");
            _options = options ?? new Dictionary("links", true);
        }

        [PreserveCase, PreserveName]
        public jQueryObject Content()
        {
            new Await()
                .WaitDx(delegate { return ThemeYoshi.Pages != null; }, 30000)    // TODO: should throw exception if the wait fails
                .AddFn(Build)
                .Commit();
            return Element;
        }

        private void Build()
        {
            if ((bool) _options["links"])
            {
                PagesD pgs = (PagesD)(object)ThemeYoshi.Pages;
                foreach (KeyValuePair<string, PageD> pg in pgs.pages)
                {
                    if (!pg.Value.Visible)
                        continue;
                    string linkFace = pg.Value.Face ?? pg.Value.Name;
                    string pageClass = pg.Value.Class ?? "VirtualPage";
                    string pageName = pg.Value.Name ?? "Page";
                    NewLink(linkFace, pageClass, pageName)
                        .AppendTo(Element)
                        .AddClass("BarLink")
                        ;
                }

            }
        }

        public static jQueryObject NewLink(string face, string pageClass, string pageName)
        {
            jQueryObject lnk = jQuery.FromHtml("<a/>")
                //.Attribute("href", Uri.AddPair(Uri.Path(Window.Location.Href), "page", pageName))
                .Attribute("href", "javascript:;")
                .Html(Transform.Htmlize(face))
                .Plugin<Jewl>().SwallowClick(delegate { Master.GoPage(pageClass, pageName); })
                ;

            if (ThemeYoshi.CurrentPageName == pageName)
                lnk.AddClass("CurrentPage");
            return lnk;
        }
    }
}
